package com.xuecheng.filesystem.service;

import com.alibaba.fastjson.JSON;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.github.tobato.fastdfs.service.TrackerClient;
import com.xuecheng.filesystem.dao.FileSystemRepository;
import com.xuecheng.framework.domain.filesystem.FileSystem;
import com.xuecheng.framework.domain.filesystem.response.FileSystemCode;
import com.xuecheng.framework.domain.filesystem.response.UploadFileResult;
import com.xuecheng.framework.exception.CustomException;
import com.xuecheng.framework.model.response.CommonCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author jl
 * @description
 * @date 2019-08-29 16:41
 */
@Service
public class FileSystemService {
    @Autowired
    private FileSystemRepository fileSystemRepository;

    private static final Logger LOGGER = LoggerFactory.getLogger(FileSystemService.class);

    private static final List<String> CONTENT_TYPE = Arrays.asList("image/jpeg","image/gif","image/png","application/x-png");

    @Autowired
    private FastFileStorageClient storageClient;

    /**
     * 上传文件
     */
    public UploadFileResult uploadFile(MultipartFile multipartFile, String businesskey, String filetag, String metadata){
        if (multipartFile == null) {
            throw new CustomException(FileSystemCode.FS_UPLOADFILE_FILEISNULL);
        }
        //1.将文件上传到fastDFS,得到文件id
        String fileId = uploadToFastDFS(multipartFile);
        if (StringUtils.isEmpty(fileId)) {
            throw new CustomException(FileSystemCode.FS_UPLOADFILE_SERVERFAIL);
        }
        //2.将文件id和其它信息存储到mongo
        FileSystem fileSystem =new FileSystem();
        fileSystem.setFileId(fileId);
        fileSystem.setFilePath(fileId);
        fileSystem.setFiletag(filetag);
        fileSystem.setBusinesskey(businesskey);
        fileSystem.setFileName(multipartFile.getOriginalFilename());
        fileSystem.setFileType(multipartFile.getContentType());
        if (StringUtils.isNotEmpty(metadata)) {
            try {
                Map map = JSON.parseObject(metadata, Map.class);
                fileSystem.setMetadata(map);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        fileSystemRepository.save(fileSystem);
        return new UploadFileResult(CommonCode.SUCCESS,fileSystem);
    }

    /**
     * 上传文件到fastDFS
     */
    private String uploadToFastDFS(MultipartFile file) {
        //校验文件类型
        String originalFilename = file.getOriginalFilename();
        String contentType = file.getContentType();
        if (!CONTENT_TYPE.contains(contentType)){
            LOGGER.info("文件类型不合法:{}",originalFilename);
            return null;
        }

        try {
            //校验文件内容
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read == null) {
                LOGGER.info("文件内容不合法:{}",originalFilename);
                return null;
            }
            //保存 D:\Download
            //file.transferTo(new File("D:\\Download\\"+originalFilename));

            //保存到fastDFS
            String ext = StringUtils.substringAfterLast(originalFilename,".");
            StorePath path = storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
            //返回fileId
            return path.getFullPath();
        } catch (IOException e) {
            LOGGER.info("服务器内部错误:{}",originalFilename);
            e.printStackTrace();
        }
        return null;
    }

}
